package com.wechat.task;

import com.github.binarywang.wxpay.bean.entpay.EntPayResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.wechat.entity.Question;
import com.wechat.entity.User;
import com.wechat.entity.UserWithdrawcashRecords;
import com.wechat.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 定时提现任务
 *
 * @author cgc
 * @date 2018/5/7
 */
@Component
public class UserWithdrawcashTask {

    private final Logger LOG = LoggerFactory.getLogger(UserWithdrawcashTask.class);

    @Autowired
    private UserWithdrawcashService userWithdrawcashService;
    @Autowired
    private UserService userService;
    @Autowired
    private PayService payService;

    @Scheduled(cron = "0 0 17 ? * MON-FRI")
    public void questionRefund() {

        LOG.info("[UserWithdrawcashTask]Start");

        try {
            List<UserWithdrawcashRecords> list = userWithdrawcashService.list(null,0,null,null,null,null);

            int right = 0;
            int wrong = 0;

            for(UserWithdrawcashRecords withdrawcashRecord : list){

                User user = userService.findById(withdrawcashRecord.getUserId());

                EntPayResult entPayResult = new EntPayResult();
                try {
                    entPayResult = payService.miniAppEntPay(String.valueOf(withdrawcashRecord.getId()), user.getOpenId(), withdrawcashRecord.getRealFee().multiply(new BigDecimal(100)).intValue(), "账户余额提现");
                }catch (WxPayException e) {
                    LOG.error("[UserWithdrawcashTask]error",e);
                    wrong += 1;
                    continue;
                }
                if(!StringUtils.isEmpty(entPayResult.getPaymentNo())){

                    Date date = new Date();
                    SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        date=formatter.parse(entPayResult.getPaymentTime());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                    withdrawcashRecord.setTradeNo(entPayResult.getPaymentNo());
                    withdrawcashRecord.setPayTime(date);
                    withdrawcashRecord.setDataState(1);
                    userWithdrawcashService.update(withdrawcashRecord);

                    right += 1;
                }
            }

            LOG.info("[UserWithdrawcashTask]end:right=" + right + ";wrong=" + wrong);
        }catch (Exception e){
            LOG.error("[UserWithdrawcashTask]error",e);
        }

    }
}
